<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" @change="changeQueryDeviceType">
          <el-option
              v-for="dict in device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="阈值类型" prop="dictValue">
        <el-select v-model="queryParams.dictValue" placeholder="请选择阈值类型" clearable>
          <template v-for="dict in queryThresholdType" :key="dict.value">
            <el-option
                :label="dict.label"
                :value="dict.value"
            />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="showStatus" v-if="showStatus">
        <el-select v-model="queryParams.showStatus" placeholder="请选择" clearable>
          <template v-for="dict in show_status" :key="dict.value">
            <el-option
                :label="dict.label"
                :value="dict.value"
            />
          </template>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['coal:thresholdData:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['coal:thresholdData:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['coal:thresholdData:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Close"
            @click="handleClose"
        >关闭</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="thresholdDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="阈值类型" align="center" prop="dictValue">
        <template #default="scope">
          <dict-tag v-if="scope.row.deviceType === '3'" :options="binocular_radar_function" :value="scope.row.dictValue"/>
          <dict-tag v-else-if="scope.row.deviceType === '5'" :options="sieve_radar_function" :value="scope.row.dictValue"/>
          <span v-else>未知类型</span>
        </template>
      </el-table-column>
      <el-table-column label="阈值" align="center" prop="thresholdValue">
        <template #default="scope">
          <span>{{ scope.row.thresholdValue.toFixed(2) }}</span>
        </template>

      </el-table-column>
      <el-table-column label="比较关系" align="center" prop="compareType">
        <template #default="scope">
          <dict-tag :options="com_compare_type" :value="scope.row.compareType"/>
        </template>
      </el-table-column>
      <el-table-column label="升级时间" align="center" prop="levelInterval" width="80">
        <template #default="scope">
          <span>{{ scope.row.levelInterval + 'h' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示" align="center" prop="showStatus" v-if="showStatus">
        <template #default="scope">
          <dict-tag :options="show_status" :value="scope.row.showStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['coal:thresholdData:edit']"
          >修改</el-button>
          <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['coal:thresholdData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改阈值数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="thresholdDataRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" @change="changeDeviceType">
            <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值类型" prop="dictValue">
          <el-select v-model="form.dictValue" placeholder="请选择阈值类型" aria-readonly="true">
            <el-option
                v-for="dict in thresholdType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="阈值" prop="thresholdValue">
          <el-input-number v-model="form.thresholdValue" :precision="2" :step="0.01" :min="0"  />
          <template v-for="(dict,index) in thresholdType" :key="index">
            <span v-if="dict.value === form.dictValue" style="margin-left: 5px">{{ dict.unit }}</span>
          </template>
        </el-form-item>
        <el-form-item label="升级时间" prop="levelInterval">
          <el-input-number v-model="form.levelInterval" :precision="0" :step="1" :min="0"  />
          <span style="margin-left: 5px">h</span>
        </el-form-item>
        <el-form-item label="比较关系" prop="compareType">
          <el-select v-model="form.compareType" placeholder="请选择比较关系">
            <el-option
                v-for="dict in com_compare_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示" prop="showStatus" v-if="showStatus">
          <el-select v-model="form.showStatus" placeholder="是否显示">
            <template v-for="dict in show_status" :key="dict.value">
              <el-option
                  :label="dict.label"
                  :value="dict.value"
              />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ThresholdData">
import { listThresholdData, getThresholdData, delThresholdData, addThresholdData, updateThresholdData,getDeviceAgreement } from "@/api/coal/thresholdData";
import { computed } from 'vue'

const { proxy } = getCurrentInstance();
const { compare_type, show_status, device_type, binocular_radar_function,sieve_radar_function } = proxy.useDict('compare_type', 'show_status',"device_type","binocular_radar_function","sieve_radar_function");

const thresholdDataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const showStatus = ref(false);
const alarmType = ref([])
const thresholdType = ref([])
const queryThresholdType = ref([])


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceType: null,
    dictValue: null,
    thresholdValue: null,
    compareType: null,
    showStatus: null,
  },
  rules: {
    deviceType: [
      { required: true, message: '请选择设备类型', trigger: 'change', },
    ],
    dictValue: [
      { required: true, message: '请选择阈值类型', trigger: 'change', },
    ],
    thresholdValue:[
      { required: true, message: "阈值不能为空", trigger: "blur" }
    ],
    levelInterval:[
      { required: true, message: "升级时间不能为空", trigger: "blur" }
    ],
    compareType: [
      { required: true, message: '请选择比较关系', trigger: 'change', },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询阈值数据列表 */
function getList() {
  loading.value = true;
  listThresholdData(queryParams.value).then(response => {
    thresholdDataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    dictValue: null,
    thresholdValue: 0.00,
    levelInterval: 24,
    compareType: null,
    showStatus: '1',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("thresholdDataRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加阈值数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  getThresholdData(id).then(response => {
    form.value = response.data;
    let dictValue = form.value.dictValue+ ''
    changeDeviceType(form.value.deviceType)
    form.value.dictValue = dictValue
    open.value = true;
    title.value = "修改阈值数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["thresholdDataRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateThresholdData(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addThresholdData(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除阈值数据编号为"' + _ids + '"的数据项？').then(function() {
    return delThresholdData(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coal/thresholdData/export', {
    ...queryParams.value
  }, `thresholdData_${new Date().getTime()}.xlsx`)
}

const com_compare_type=computed(()=>{
  let newArray = [];
  compare_type.value.forEach(dict=>{
    dict.label=dict.label.replace("eq","=").replace("gt",">").replace("ge",">=").replace("lt","<").replace("le","<=")
    newArray.push(dict)
  })
  return newArray;
})

// 返回按钮
function handleClose() {
  const obj = { path: "/facility/device" };
  proxy.$tab.closeOpenPage(obj);
}

function initAlarmType(){
  // 3 双目雷达 5 筛机雷达
  let deviceTypes = "3,5"
 return (
  getDeviceAgreement(deviceTypes).then(resp=>{
    alarmType.value = resp.data;
  })
 )
}

function changeDeviceType(deviceType){
  form.value.dictValue = ''
  if (deviceType === '3'){
    thresholdType.value = binocular_radar_function.value.filter(item => item.type === '1' || item.type === '3')
  } else if (deviceType === '5'){
    thresholdType.value = sieve_radar_function.value.filter(item => item.type === '3')
  } else {
    thresholdType.value = []
  }
}

function changeQueryDeviceType(deviceType){
  queryParams.value.dictValue = ''
  if (deviceType === '3'){
    queryThresholdType.value = binocular_radar_function.value.filter(item => item.type === '1' || item.type === '3')
  } else if (deviceType === '5'){
    queryThresholdType.value = sieve_radar_function.value.filter(item => item.type === '1' || item.type === '3')
  } else {
    queryThresholdType.value = []
  }
}

onMounted(() => {
  showStatus.value = proxy.$auth.hasRole('admin');
  if (!showStatus.value){
    queryParams.value.showStatus = '1'
  }
  queryParams.value.params = {}
  queryParams.value.params.thresholdType='1'
  getList()

})

</script>
